<template>
  <main>

    <!-- 通用头部 -->
    <c-header :btns="btns" @btnAct="btnAct" />
    <!-- <dg-header /> -->

    <!-- 主体内容 -->
    <news />

    <!-- 注册、登录模态框 -->
    <modal :modalVisible.sync="modalVisible" :width="380">

      <div slot="header">设 计 师 登 录</div>

      <am-form slot="body">
        <am-input-group :block="true">
          <!-- <label>大赛帐号</label> -->
          <am-input v-model="modalForm.loginID" placeholder="请输入手机号码" autocomplete="off"></am-input>
          <am-input-label slot="prepend" transparent>手机号码：</am-input-label>
        </am-input-group>
        <am-input-group :block="true">
          <!-- <label>密码</label> -->
          <span style="width: 100%;" @keyup.enter="login(false)">
            <am-input v-model="modalForm.password" type="password" placeholder="请输入您的密码" ></am-input>
          </span>
          <am-input-label slot="prepend" transparent>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码：</am-input-label>
        </am-input-group>
      </am-form>

      <p>忘记帐号密码请联系相关人员</p>

      <template slot="footer">
        <am-button color='primary' @click="login">登录</am-button>
        <am-button color='default' @click="register">注册</am-button>
      </template>
    </modal>

  </main>
</template>


<script>
// import DgHeader from '@/dg_components/topbar/DgHeader'
import Header from '@/components/Header'
import Modal from '@/components/Modal'
// import News from '@/views/home/News'
const News = () => import('@/views/home/News')// 仅针对首页优化

import md5 from 'md5'
import { getIPv4, getBrowser, getOPTC } from '@/util/util'

/**
 * @description - 非实例数据
 */
let isFromRegister = false;// 是否从注册窗口回来
let browser = void 0;// 浏览器信息

export default {
  name: 'home',
  data() {
    return {
      modalVisible: false,// 登录模态框
      modalForm: {// 登录模态框表单
        loginID: '',
        password: '',
      },


      /**
       * 非响应式属性使用
       */
      btns: [{// 未登录按钮
        name: '我是设计师',
        act: 'showModal'
      }],
      funs: {// btnAct反应动作
        'showModal': this.showModal,// 显示模态框
        'logout': this.logout,// 登出
      }
    }
  },
  computed: {
    loginID() {// 为注册页返回服务
      return this.$store.state.designer.loginID;
    }
  },
  components: {
    Modal, News,
    CHeader: Header,
  },
  methods: {
    ready() {
      this.isFromRegister();
      this.isCookiesLogin();
      this.setBrowser();
      this.setIP();
    },

    /**设置浏览器信息 */
    setBrowser() {
      this.$store.commit('setBrowser', browser);
    },
    /**设置ipv4 */
    setIP() {
      getIPv4(ip => this.$store.commit('setIPv4', ip), msg => window.alert(msg));
    },


    /**是否从注册跳转来 */
    isFromRegister() {
      if(isFromRegister && this.loginID !== '') {
        this.$cookies.remove("designer");// 100%不使用cookie登录
        this.modalForm.loginID = this.loginID;
        this.modalForm.password = '';
      }
    },

    /**是否使用cookies登录 */
    isCookiesLogin() {
      if(this.$cookies.isKey("designer")) {
        this.login(true);
      }
    },

    /**
     * header emit
     */
    btnAct(name) {
      console.log('home-btnAct: ' + name);
      this.funs[name]();
    }, 
    /**进行登录 */
    login(isCookie = false) {
      let _ins = { close() {} }
      const delay = 399;

      /**登录请求 */
      const goLogin = (loginID, password) => {
        _ins = this.$loading({ loadingText: '正在登录' });
        // 这里继续封装为一个Promise也可以
        return this.dgpost(this.api.LOGIN, {
          loginID, password: md5(password)
        }).then(res => {
          return Promise.resolve(res.data.data);
        }).catch(() => {
          this.$message({
            title: '登录失败',
            type: 'warning',
            message: '帐号密码错误',
            closeable: true
          });
        });
      }

      /**登录成功回调 */
      const loginHandle = ({ loginID, designerID, isJoin, designerName }) => {

        const data = { loginID, designerID, isJoin: +isJoin, designerName }

        // 设置cookie，12h失效
        this.$cookies
        .set('designer', JSON.stringify(data), (60 * 60 * 12));

        // 单一状态设置
        for(const key in data) {
          this.$store.commit('setDesigner', {key, val: data[key]})
        }


        // 替换按钮
        const logoutBtn = {
          name: '退出',
          act: 'logout',
        }
        const personalBtn  = {
          name: designerName + '_个人中心',
          href: '/personal'
        }

        // 登录后替换“我是设计师”按钮
        this.btns
        .splice(this.btns.findIndex(btn => btn.name === '我是设计师'), 1, logoutBtn, personalBtn);

        // 完成登录
        _ins.close();

        // 登录表单清空
        this.modalForm.loginID = '';
        this.modalForm.password = '';
      }

      /**
       * MAIN
       * co act a gen
       * @description co函数
       */
      this.co(function* () {
        if(isCookie) {// cookie登录
          console.log('cookie login');

          // this.$store.state.designer;
          const {
            loginID, designerID, isJoin, designerName
          } = JSON.parse(this.$cookies.get('designer'));
          loginHandle({loginID, designerID, isJoin, designerName});
        } else {// 新登录
          console.log('new login');

          const {// 模态框的登录信息
            loginID, password
          } = {
            loginID: this.modalForm.loginID,
            password: this.modalForm.password
          }

          if(![loginID, password].hasEmpty()) {
            const { designerID, isJoin, designerName } = yield goLogin(loginID, password);
            loginHandle({loginID, designerID, isJoin, designerName});
            this.$notify({
              message: '登录成功',
              type: 'success',
              delay
            });

            setTimeout(() => {
              this.modalVisible = false;
            }, (delay * 2));
          } else {
            this.$notify({
              message: '你确定你填完？',
              type: 'warning',
              delay: (delay * 3)
            });
          }
        }
      }).catch(err => {
        this.logout(false);
        console.error(err);
        _ins.close();
      });
    },
    /**退出 */
    logout(isReplace = true) {

      /**
       * 1. 清除cookie
       * 1. 清除单一状态designer
       * 1. 按钮替换
       */

      // 清楚cookie
      this.$cookies.remove("designer");

      // 清除单一状态designer
      this.$store.commit('removeDesigner');

      // 替换按钮
      const loginBtn = {
        name: '我是设计师',
        act: 'showModal'
      }

      // 退出后，
      if(isReplace) {
        this.btns.splice(this.btns.findIndex(btn => btn.name === '个人中心'), 1, loginBtn);
        this.btns.splice(this.btns.findIndex(btn => btn.name === '退出'), 1);
      }

      // 登录表单清空
      this.modalForm.loginID = '';
      this.modalForm.password = '';
    },
    /**注册页面跳转 */
    register() {
      this.modalVisible = false;
      setTimeout(() => {
        this.$router.push('/register');
      }, 199);
    },
    /**显示模态框 */
    showModal() {
      this.modalVisible = true;
    }
  },
  mounted() {
    this.ready();
  },


  /**
   * @description -
   * - ie8以下的浏览器都不合格
   * - 判断是否从注册页过来
   * 
   * 注意无法获取this
   */
  beforeRouteEnter(to, from, next) {
    browser = getBrowser();
    if(browser !== 'IE8' && browser !== 'IE<7' && getOPTC(browser) !== 'undefined') {
      if(from.name === 'Register') {
        isFromRegister = true;
      }
      next();
    } else if(getOPTC(browser) === 'undefined') {
      window.alert('无法获取你的浏览器信息，请修复或使用其他浏览器');
      window.location.href = 'about:blank';
    } else {
      window.alert(`你的浏览器版本过低（${ browser }），请使用ie9+或主流浏览器`);
      window.location.href = 'about:blank';
    }
  }
}
</script>